package routers

import (
	"github.com/gin-gonic/gin"
	"go-vue/admin/apis/sv1"
	"go-vue/admin/utils"
	"net/http"
)

func Router(router *gin.Engine) {
	//服务器检测接口
	router.GET("/ok", func(ctx *gin.Context) {
		utils.OutSuccess(ctx, nil)
	})
	V1(router)
}

// V1 系统自动方法
//包含登录 用户管理，角色管理 菜单管理
func V1(router *gin.Engine) {
	v1 := router.Group("/v1")

	//登录
	user := new(sv1.User)
	v1.Any("/token", user.Login)

	authApi := v1.Use(CheckJwt)

	//菜单管理
	menu := new(sv1.Menu)
	v1.Any("system/menu/my/:ver", menu.MyMenu) //获取我的菜单
	authApi.Any("/system/menu/list", menu.EditList)
	authApi.Any("/system/menu/save", menu.EditSave)
	authApi.Any("/system/menu/sort", menu.EditSort)
	authApi.Any("/system/menu/delete", menu.EditDel)

	//角色管理
	role := new(sv1.Roles)
	authApi.Any("/system/role/init", role.InitList)
	authApi.Any("/system/role/list", role.EditList)
	authApi.Any("/system/role/save", role.EditSave)
	authApi.Any("/system/role/delete", role.EditDel)
	authApi.Any("/system/menu/permission", role.EditListPermission)
	authApi.Any("/system/menu/psave", role.EditSavePermission)

	//部门管理
	depart := new(sv1.Depart)
	authApi.Any("/system/depart/init", depart.InitList)
	authApi.Any("/system/depart/list", depart.EditList)
	authApi.Any("/system/depart/save", depart.EditSave)
	authApi.Any("/system/depart/sort", depart.EditSort)
	authApi.Any("/system/depart/delete", depart.EditDel)

	//用户管理
	authApi.Any("/user/member/list", user.EditList)
	authApi.Any("/user/member/save", user.EditSave)
	authApi.Any("/user/member/delete", user.EditDel)
	authApi.Any("/user/member/setp", user.EditSetPwd)

	//系统配置
	config := new(sv1.Config)
	authApi.Any("/system/config/list", config.EditList)
	authApi.Any("/system/config/save", config.EditSave)
}

// Cors 处理跨域请求,支持options访问
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method

		//Access-Control-Expose-Headers <- 允许用户可以读取哪一些 Header
		//Access-Control-Allow-Origin <- 允许哪些域名可以发送请求
		//Access-Control-Allow-Headers <- 允许请求带上哪一些 Header
		//Access-Control-Allow-Methods <- 允许哪些方式发送请求(Get Post Put...等)
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization")
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type, Newauthorization")
		c.Header("Access-Control-Allow-Credentials", "true")

		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		// 处理请求
		c.Next()
	}
}
